﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using WindowsLive.Writer.Api;

namespace InsertFromSkyDrive
{
    public partial class frmMain : Form
    {
        PluginSettings m_settings;
        string code = "";
        string cid = "";
        string folder = "";
        string[] codes = { "<iframe scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" style=\"width:240px;height:66px;margin:3px;padding:0;border:1px solid #dde5e9;background-color:#ffffff;\" src=\"{0}\"></iframe>",
                           "<iframe scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" style=\"width:94px;height:94px;margin:3px;padding:0;border:1px solid #dde5e9;background-color:#ffffff;\" src=\"{0}\"></iframe>",
                           "<iframe scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" style=\"width:240px;height:26px;margin:3px;padding:0;border:1px solid #dde5e9;background-color:#ffffff;\" src=\"{0}\"></iframe>"};
        string[] divs = {"<div marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" style=\"position:relative;width:240px;height:66px;margin:3px;padding:0;border:1px solid #dde5e9;background-color:#ffffff;\">{0}</div>",
                           "<div marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" style=\"position:relative;width:94px;height:94px;margin:3px;padding:0;border:1px solid #dde5e9;background-color:#ffffff;\">{0}</div>",
                           "<div marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" style=\"position:relative;width:240px;height:26px;margin:3px;padding:0;border:1px solid #dde5e9;background-color:#ffffff;\">{0}</div>"};
        string[] urls = { "http://{0}.skydrive.live.com/embedrowdetail.aspx/{1}", "http://{0}.skydrive.live.com/embedgrid.aspx/{1}", "http://{0}.skydrive.live.com/embedrow.aspx/{1}" };

        public frmMain(PluginSettings settings)
        {
            m_settings = settings;
            InitializeComponent();
            windowsLiveID1.FirstRun(m_settings, false, txbxLinkFromBrowse);
        }

        public string FinalEmbedCode
        {
            get { return code; }
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            string t = txbxLink.Text;
            if (txbxLink.Text == string.Empty && txbxLinkFromBrowse.Text != string.Empty)
                t = windowsLiveID1.Url;
            
            // Check if the text box is empty
            if (t == string.Empty)
            {
                MessageBox.Show("Sorry, you haven't entered a link.", "Big Fat Hairy Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Check whether the link is public or not, if it is, it won't be a secure link
            if(t.StartsWith("https://"))
                MessageBox.Show("Sorry, you haven't entered a public SkyDrive link.", "Big Fat Hairy Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            
            // Check it's a valid SkyDrive link
            Match m = Regex.Match(t, @"http://.*\.skydrive.live.com/");
            if (!m.Success)
            {
                MessageBox.Show("Sorry, you haven't entered a valid SkyDrive link.", "Big Fat Hairy Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                GetCode(t);
                this.DialogResult = DialogResult.OK;
                this.Close();
            }

        }

        private void GetCode(string link)
        {
            cid = link.Substring(7, link.IndexOf(".skydrive") - 7);
            folder = link.Substring(link.IndexOf(".aspx/") + 6);
            int s = 0;

            if (rbStyleOne.Checked)
                s = 0;
            else if (rbStyleTwo.Checked)
                s = 1;
            else if (rbStyleThree.Checked)
                s = 2;

            string url = string.Format(urls[s], cid, folder);

            if (!chkiframe.Checked)
            {
                StringBuilder sb = new StringBuilder();                
                PluginHttpRequest req = new PluginHttpRequest(url);
                Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                // Pipe the stream to a higher level stream reader with the required encoding format. 
                StreamReader readStream = new StreamReader(req.GetResponse(), encode);
                Char[] read = new Char[256];
                int count = readStream.Read(read, 0, 256);
                while (count > 0)
                {
                    sb.Append(read, 0, count);
                    count = readStream.Read(read, 0, 256);
                }
                readStream.Close();
                string html = sb.ToString();
                html = html.Remove(0, (html.IndexOf("<st") - 1));
                html = html.Remove((html.IndexOf("</bo") - 1));
                html = html.Replace("/images/ecRowDet_bg.png", "http://skydrive.live.com/images/ecRowDet_bg.png");
                html = html.Replace("/images/ecRow_bg.png", "http://skydrive.live.com/images/ecRow_bg.png");
                html = html.Replace("/images/ecGrid_bg.png", "http://skydrive.live.com/images/ecGrid_bg.png");
                code = string.Format(divs[s], html);
            }
            else code = string.Format(codes[s], url);

        }

    }
}
